package com.syj.jsxjj.ui.authentication.activity;

import android.animation.ObjectAnimator;
import android.content.Intent;
import android.support.v4.content.ContextCompat;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.syj.jsxjj.config.Constant;
import com.syj.jsxjj.events.AuthenticationRefreshEvent;
import com.syj.jsxjj.events.UIBaseEvent;
import com.syj.jsxjj.ui.authentication.bean.AuthenticationinformationBean;
import com.syj.jsxjj.ui.authentication.bean.PertfecInformationRequestBean;
import com.syj.jsxjj.util.StringUtil;
import com.syj.jsxjj.R;
import com.syj.jsxjj.app.App;
import com.syj.jsxjj.base.BaseActivity;
import com.syj.jsxjj.dialog.AlertFragmentDialog;
import com.syj.jsxjj.events.FragmentRefreshEvent;
import com.syj.jsxjj.ui.authentication.adapter.PerfectInformationAdapter;
import com.syj.jsxjj.ui.authentication.adapter.PerfectMustInfoAdapter;
import com.syj.jsxjj.ui.authentication.contract.PertfecInformationContract;
import com.syj.jsxjj.ui.authentication.presenter.PerfectInformationPresenter;
import com.syj.jsxjj.ui.main.WebViewActivity;
import com.syj.jsxjj.util.StatusViewUtil;
import com.syj.jsxjj.widget.RoundProgressBar;
import com.syj.jsxjj.widget.loading.LoadingLayout;
import com.syj.jsxjj.widget.recycler.BaseRecyclerAdapter;
import com.syj.jsxjj.widget.recycler.DividerItemDecoration;
import com.tendcloud.tenddata.TCAgent;
import com.umeng.analytics.MobclickAgent;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

import static com.syj.jsxjj.http.HttpManager.getUrl;
import static com.syj.jsxjj.util.ToastUtil.showToast;


/**
 * 认证中心
 */
public class PerfectInformationActivity extends BaseActivity<PerfectInformationPresenter> implements PertfecInformationContract.View {
    @BindView(R.id.loading_layout)
    LoadingLayout mLoadingLayout;
    @BindView(R.id.swipe_target)
    RecyclerView mSwipeTarget;
    @BindView(R.id.refresh)
    SwipeRefreshLayout mRefresh;
    @BindView(R.id.recycler_must_view)
    RecyclerView mRecyclerMustList;
    @BindView(R.id.ll_down_anim)
    LinearLayout mDownAnimLayout;
    @BindView(R.id.ll_tip_show)
    LinearLayout mTipShowLayout;
    @BindView(R.id.ll_up_anim)
    LinearLayout mUpAnimLayout;
    @BindView(R.id.progress_round)
    RoundProgressBar mProgress;
    @BindView(R.id.tv_tipOne)
    TextView mTipOneText;
    @BindView(R.id.iv_tipOne)
    ImageView mTipOneImage;
    @BindView(R.id.tv_progress)
    TextView mProgressText;
    private int contactStatus;
    private int realVerifyStatus;
    private int zhimaStatus;
    private int height;//展开选填项列表的高度
    private int mustNum;//认证必填项数量
    private int finishProgress;//完成进度值
    private PerfectInformationAdapter mAdapter;
    private PerfectMustInfoAdapter mMustAdapter;
    private DividerItemDecoration itemDecoration;
    private List<AuthenticationinformationBean> items;
    private List<AuthenticationinformationBean> mustBeItems;

    @Override
    public int getLayoutId() {
        return R.layout.activity_perfect_information;
    }

    @Override
    public void initPresenter() {
        mPresenter.init(this);
    }

    @Override
    public void loadData() {
        EventBus.getDefault().register(this);
        initView();
        iniLister();

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().post(new FragmentRefreshEvent(UIBaseEvent.REFRESHINDEX));
        EventBus.getDefault().unregister(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
        mPresenter.getPertfecInformation();
        MobclickAgent.onEvent(this, "perfect_authentication");
        TCAgent.onEvent(this, "perfect_authentication");
    }


    private void iniLister() {

        mRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                //请求接口
                mPresenter.getPertfecInformation();
            }
        });
        mPresenter.getPertfecInformation();
//        mRefresh.setLoadMoreEnabled(false);
    }

    /**
     * 初始化titile
     */
    private void initView() {
        mTitle.setTitle(R.string.perfect_information);
        mRefresh.setColorSchemeColors(ContextCompat.getColor(mContext, R.color.theme_color));
        mAdapter = new PerfectInformationAdapter(this);
        mMustAdapter = new PerfectMustInfoAdapter(this);
        mSwipeTarget.setLayoutManager(new LinearLayoutManager(mContext));
        mRecyclerMustList.setLayoutManager(new GridLayoutManager(this, 2));
        itemDecoration = new DividerItemDecoration(mContext, DividerItemDecoration.VERTICAL_LIST);
        mSwipeTarget.addItemDecoration(itemDecoration);
        mSwipeTarget.setAdapter(mAdapter);
        mRecyclerMustList.setAdapter(mMustAdapter);
        mSwipeTarget.setVisibility(View.GONE);
        setAnim(mTipOneText);
        setAnim(mTipOneImage);
        itemClick();
        if (!StringUtil.isBlank(getIntent().getStringExtra("show"))) {
            mSwipeTarget.setVisibility(View.VISIBLE);
            mDownAnimLayout.setVisibility(View.GONE);
            mUpAnimLayout.setVisibility(View.VISIBLE);
            mTipShowLayout.setVisibility(View.VISIBLE);
        }
    }

    private void itemClick() {
        mMustAdapter.setOnItemClickListener(new BaseRecyclerAdapter.OnItemClick() {
            @Override
            public void onItemClick(View view, int position) {
                if (position == 0) {
                    MobclickAgent.onEvent(mContext, "PERSONAL");
                    TCAgent.onEvent(mContext, "PERSONAL");
                } else if (position == 1) {
                    MobclickAgent.onEvent(mContext, "CONTACT");
                    TCAgent.onEvent(mContext, "CONTACT");
                } else if (position == 2) {
                    MobclickAgent.onEvent(mContext, "PHONE");
                    TCAgent.onEvent(mContext, "PHONE");
                } else if (position == 3) {
                    MobclickAgent.onEvent(mContext, "ZMXY");
                    TCAgent.onEvent(mContext, "ZMXY");
                }
                AuthenticationinformationBean item = mMustAdapter.getData().get(position);
                int type = item.getTag();//得到所以列表的type
                Intent intent = new Intent(PerfectInformationActivity.this, WebViewActivity.class);
                if (Constant.TAG_QUOTA_PERSONAL == type) { // 个人信息
                    intent.setClass(PerfectInformationActivity.this, PersonalInformationActivity.class);
                } else if (Constant.TAG_QUOTA_CONTACT == type) {//紧急联系人
                    if (realVerifyStatus == 1) { //是否实名认证
                        intent.setClass(PerfectInformationActivity.this, AuthEmergencyContactActivity.class);
                    } else {
                        showDialog("亲，请先填写个人信息哦~");
                        return;
                    }
                } else if (Constant.TAG_QUOTA_PHONE == type) {//手机运营商
                    if (realVerifyStatus == 1) { //是否实名认证
                        if (mMustAdapter.getData().get(position).getStatus() == 1) { //运营商是否已认证
                            intent.putExtra("url", getUrl(item.getUrl()) + "&recode=2");
                        } else {
                            if (contactStatus == 1) {//紧急联系人是否已认证
                                intent.putExtra("url", item.getUrl());
                            } else {
                                showDialog("亲，请先填写紧急联系人哦~");
                                return;
                            }
                        }
                    } else {
                        showDialog("亲，请先填写个人信息哦~");
                        return;
                    }
                } else if (Constant.TAG_QUOTA_ZMXY == type) {//芝麻信用
                    if (realVerifyStatus == 1) {
                        intent.putExtra("url", item.getUrl());
                    } else {
                        showDialog("亲，请先填写个人信息哦~");
                        return;
                    }
                }
                startActivity(intent);
            }
        });
        //选填项判断：
        mAdapter.setOnItemClickListener(new BaseRecyclerAdapter.OnItemClick() {
            @Override
            public void onItemClick(View view, int position) {
                if (position == 0) {
                    MobclickAgent.onEvent(mContext, "WORK");
                    TCAgent.onEvent(mContext, "WORK");
                } else if (position == 1) {
                    MobclickAgent.onEvent(mContext, "ALIPAY");
                    TCAgent.onEvent(mContext, "ALIPAY");
                } else if (position == 2) {
                    MobclickAgent.onEvent(mContext, "MORE");
                    TCAgent.onEvent(mContext, "MORE");
                }
                AuthenticationinformationBean item = mAdapter.getData().get(position);
                int type = item.getTag();//得到所以列表的type
                Intent intent = new Intent(PerfectInformationActivity.this, WebViewActivity.class);
                if (Constant.TAG_QUOTA_WORK == type) {//工作信息
                    intent.setClass(PerfectInformationActivity.this, LendWorkDetailsActivity.class);
                } else if (Constant.TAG_QUOTA_ALIPAY == type) {
                    intent.putExtra("url", item.getUrl());
                    //支付宝认证
                } else if (Constant.TAG_QUOTA_MORE == type) { //更多
                    intent.putExtra("url", item.getUrl());
                }
                startActivity(intent);
            }
        });
    }

    public void setAnim(View view) {
        ObjectAnimator animator = ObjectAnimator.ofFloat(view, "translationY", 0, 25, 0);
        animator.setDuration(800);
        animator.setRepeatCount(-1);
        animator.start();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void refreshPerfectInfo(AuthenticationRefreshEvent event) {
        mPresenter.getPertfecInformation();
    }

    @Override
    public void PertfecInformationSccess(PertfecInformationRequestBean bean) {
        mLoadingLayout.setStatus(LoadingLayout.Success);
        mustNum = bean.getItem().getMustBeCount();
        contactStatus = bean.getItem().getContacts_status();
        realVerifyStatus = bean.getItem().getReal_verify_status();
        items = bean.getItem().getNoMustBeList();
        mustBeItems = bean.getItem().getIsMustBeList();
//        finishProgress =mustNum;
        mProgress.setAnimProgress(mustNum, false);
        mProgressText.setText(mustNum + "%");
        StatusViewUtil.hidePopWin();
        if (items.size() > 0) {
//            mRefresh.setVisibility(View.VISIBLE);
            mAdapter.clearData();
            mMustAdapter.clearData();
            //只展示已填写item
            int position = 0;
            for(int i=0; i<items.size(); i++){
                if (!items.get(i).getOperator().contains("已填写")){
                    position++;
                    items.remove(i);
                    i--;
                }
            }
            if (position==3){//三个选填
                mUpAnimLayout.setVisibility(View.GONE);
                mSwipeTarget.setVisibility(View.GONE);
                mTipShowLayout.setVisibility(View.GONE);
                mDownAnimLayout.setVisibility(View.GONE);
            }
            mAdapter.addData(items);
            mMustAdapter.addData(mustBeItems);
        } else {
            StatusViewUtil.showDefaultPopWin(this, new StatusViewUtil.IOnTouchRefresh() {
                @Override
                public void refresh() {
                    mPresenter.getPertfecInformation();
                }
            }, StatusViewUtil.TAG_POP_STYLE_NORECORD, "暂无数据");

            mAdapter.clearData();
            mMustAdapter.clearData();
            mAdapter.addData(items);
            mMustAdapter.addData(mustBeItems);
        }
    }

    @OnClick({R.id.ll_down_anim, R.id.ll_up_anim})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.ll_down_anim:
                mSwipeTarget.setVisibility(View.VISIBLE);
                mDownAnimLayout.setVisibility(View.GONE);
                mUpAnimLayout.setVisibility(View.VISIBLE);
                mTipShowLayout.setVisibility(View.VISIBLE);
                MobclickAgent.onEvent(this, "down_anim");
                TCAgent.onEvent(this, "down_anim");
                break;
            case R.id.ll_up_anim:
                MobclickAgent.onEvent(this, "up_anim");
                TCAgent.onEvent(this, "up_anim");
//                AnimaUtil.animatorClose(mSwipeTarget, height);
                mSwipeTarget.setVisibility(View.GONE);
                mDownAnimLayout.setVisibility(View.VISIBLE);
                mTipShowLayout.setVisibility(View.GONE);
                mUpAnimLayout.setVisibility(View.GONE);
                ObjectAnimator animator = ObjectAnimator.ofFloat(mTipOneImage, "rotation", -180, -360);
                animator.setDuration(500);
                animator.start();
                break;
            default:
                break;
        }
    }

    @Override
    public void showLoading(String content) {
        if (items == null) {
            mLoadingLayout.setStatus(LoadingLayout.Loading);
        } else {
            App.loadingContent(this, content);

        }
    }

    @Override
    public void stopLoading() {
        App.hideLoading();
        if (mRefresh.isRefreshing()) {
            mRefresh.setRefreshing(false);
        }
    }

    @Override
    public void showErrorMsg(String msg, String type) {
        showToast(msg);
        if ("网络不可用".equals(msg)) {
            mLoadingLayout.setStatus(LoadingLayout.No_Network);
        } else {
            mLoadingLayout.setErrorText(msg)
                    .setStatus(LoadingLayout.Error);
        }
        mLoadingLayout.setOnReloadListener(new LoadingLayout.OnReloadListener() {
            @Override
            public void onReload(View v) {
                mPresenter.getPertfecInformation();
            }
        });
    }

    private void showDialog(String content) {
        new AlertFragmentDialog.Builder(this)
                .setContent(content)
                .setRightBtnText("确定")
                .build();
    }
}
